import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RequestService {

  constructor() { }

  // 同步
  getData(){

    return 'this is service data';
  }

  getCallbackData(cb){

    setTimeout(() => {

      const username = '张三';

      // return username;
      cb(username);

    }, 1000);

  }


  getPromiseData(){

    return new Promise((resolve) => {
      setTimeout(() => {

        const username = '张三--promise';

        resolve(username);

      }, 1000);
    });
  }

  getRxjsData(){
    return new Observable(observe => {
      setTimeout(() => {
        const username = '张三--Observable';
        observe.next(username);
        // observer.error('数据');
      }, 3000);
    });
  }

  // 多次执行
  getPromiseIntervalData() {
    return new Promise((resolve) => {
      setInterval(() => {
        const username = '张三--promise多次';
        resolve(username);
      }, 1000);
    });
  }

  getRxjsIntervalData() {
    let count = 0;
    return new Observable(observer => {

      setInterval(() => {
        count++;
        const username = '张三--Rxjs' + count;
        observer.next(username);
      }, 1000);
    });
  }

  getRxjsIntervaNum() {
    let count = 0;
    return new Observable(observer => {

      setInterval(() => {
        count++;
        observer.next(count);
      }, 1000);
    });
  }
}
